package database;

import entity.Class;
import manager.ClassManager;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Noi
 */
public class ClassManagerDB {

    private CallableStatement cstmt;
    private java.sql.Connection conn;
    private ResultSet rs;

    public ClassManagerDB(java.sql.Connection conn) {
        this.conn = conn;
    }
    
    public void loadData(ClassManager classManager) {
        try {
            cstmt = conn.prepareCall("{call sp_GetClass}");
            rs =  cstmt.executeQuery();
            while(rs.next()) {
                String classID = rs.getString("ClassID");
                int classRoomBlockID = rs.getInt("ClassRoomBlockID");
                String className = rs.getString("ClassName");
                int fromYear = rs.getInt("FromYear");
                int toYear = rs.getInt("ToYear");
                boolean status = rs.getBoolean("Status");
                Class obj = new Class(classID, classRoomBlockID, className, fromYear, toYear, status);
                classManager.add(obj);
            }
            rs.close();
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(ClassManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void deleteClass(Class obj) {
        try {
            cstmt = conn.prepareCall("{call sp_DeleteClass(?)}");
            cstmt.setString(1, obj.getClassID());
            cstmt.executeUpdate();
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(ClassManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void insertClass(Class obj) {
        try {
            cstmt = conn.prepareCall("{call sp_InsertClass(?,?,?,?,?)}");
            cstmt.setString(1, obj.getClassID());
            cstmt.setInt(2, obj.getClassRoomBlockID());
            cstmt.setString(3, obj.getClassName());
            cstmt.setInt(4, obj.getFromYear());
            cstmt.setInt(5, obj.getToYear());
            cstmt.executeUpdate();
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(ClassManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void updateClass(Class obj) {
        try {
            cstmt = conn.prepareCall("{call sp_UpdateClass(?,?,?,?,?,?)}");
            cstmt.setString(1, obj.getClassID());
            cstmt.setInt(2, obj.getClassRoomBlockID());
            cstmt.setString(3, obj.getClassName());
            cstmt.setInt(4, obj.getFromYear());
            cstmt.setInt(5, obj.getToYear());
            cstmt.setBoolean(6, obj.isStatus());
            cstmt.executeUpdate();
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(ClassManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
